package com.cskaoyan.market.controller;

import com.cskaoyan.market.db.domain.MarketRole;
import com.cskaoyan.market.service.AdminRoleService;
import com.cskaoyan.market.service.impl.AdminRoleServiceImpl;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author:yanzijun
 * @time:2024/06/18/22:22
 */
@WebServlet("/admin/role/*")
public class AdminRoleController extends HttpServlet {
    AdminRoleService adminRoleService = new AdminRoleServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String replaced = requestURI.replace(req.getContextPath() + "/admin/role/", "");
        if ("options".equals(replaced)) {
            options(req, resp);
        }
    }

    private void options(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List<MarketRole> marketRoles = adminRoleService.options();
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        for (MarketRole marketRole : marketRoles) {
            Map<String, Object> map = new HashMap<>();
            map.put("value", marketRole.getId());
            map.put("label", marketRole.getName());
            list.add(map);
        }
        Object o = ResponseUtil.okList(list);
        String s = JacksonUtil.getObjectMapper().writeValueAsString(o);
        resp.getWriter().println(s);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
